package com.lmxdawn.api.common.filter;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lmxdawn.api.common.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;



/**
 * 请求参数处理过滤器<br>
 * <p>
 * 本过滤器必须放在CacheRequestFilter之后执行
 *
 * @author jy
 * @since 2023-12-06 16:59
 */
@Slf4j
public class RequestParamFilter extends OncePerRequestFilter {

    private static final JSONObject EMPTY = new JSONObject(0);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if (WebUtils.isJsonRequest(request)) {
            Map<String, Object> addAttributes = this.getAddAttributes(request);
            this.addAttribute(request, addAttributes);
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取json对象
     *
     * @param request
     * @return
     */
    private JSONObject getJSONObject(HttpServletRequest request) {
        // 处理 json 请求内容
        String jsonText = ServletUtil.getBody(request);
        if (StringUtils.isEmpty(jsonText)) {
            return EMPTY;
        }
        if (jsonText.startsWith("{") && jsonText.endsWith("}")) {
            return JSON.parseObject(jsonText);
        }
        return EMPTY;
    }

    /**
     * 获取添加属性
     *
     * @param request 要求
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    private Map<String, Object> getAddAttributes(HttpServletRequest request) {
        Map<String, Object> addHeaders = new HashMap<>();
        JSONObject jsonObject = this.getJSONObject(request);
        addHeaders.put("tid", jsonObject.getOrDefault("tid", 0));
        addHeaders.put("ts", jsonObject.getOrDefault("ts", 0L));
        addHeaders.put("channel", jsonObject.getOrDefault("channel", 0));
        return addHeaders;
    }

    /**
     * 添加请求属性
     *
     * @param request       当前请求
     * @param addAttributes 属性值
     */
    private void addAttribute(HttpServletRequest request, Map<String, Object> addAttributes) {
        if (Objects.isNull(request) || ObjectUtils.isEmpty(addAttributes)) {
            return;
        }
        for (Map.Entry<String, Object> entry : addAttributes.entrySet()) {
            request.removeAttribute(entry.getKey());
            request.setAttribute(entry.getKey(), entry.getValue());
        }
    }

}
